<?php

class Sell extends Controller {

	function index($user_id = 0, $selected_oper_id = 0)
	{
		global $VALUTA, $USER_LEVEL;
		$user_id = intval($user_id);
		if($this->MUser->isCanOper($user_id))
		{
			$user = $this->MUser->get($user_id);
			$kurses = $this->_getKurses();
			$filters_oper = array('type' => array('buy', 'reg', 'ref', 'ng', 'patriot', 'arest', '8marta', 'modify.buy', 'week'), 'user_id' => $user['id'], 'sort' => 'date asc,id asc');
			if($user['id'] != Auth::$user_id || Auth::isSupport())
			{
				foreach($USER_LEVEL as $k => $v)
				{
					$filters_oper['type'][] = 'l'.$k;
				}
			}
			$opers = $this->MOper->getList($filters_oper);
			foreach($opers as $k => $o)
			{
				if(!canSell($o, $user))
				{
					unset($opers[$k]);
				}
			}

			$view = 'sell_2';
			$data = array('kurses' => $kurses, 'user' => $user, 'opers' => $opers, 'selected_oper_id' => $selected_oper_id);

			$root = $this->MUser->getRoot();
			$root['children'] = $this->MUser->getMyStructure($root['id']);

			$my_scheta = $this->MSchet->getList(array('user_id' => Auth::$user_id));
			foreach($my_scheta as $k => $s)
			{
				$my_scheta[$k]['name'] .= " ".$VALUTA[$s['valuta']];
			}

			$data['root'] = $root;
			$data['my_scheta'] = $my_scheta;
		}
		else
		{
			$users = $this->MUser->getChildrenAndMe(Auth::$user_id);
			$me = $this->MUser->get(Auth::$user_id);
			if(!$me['can_oper'])
			{
				unset($users[Auth::$user_id]);
			}
			$data = array('users' => $users);
			$view = 'sell_1';
		}

		$this->load->view('head', array());
		$this->load->view('oper/'.$view, $data);
		$this->load->view('foot');
	}

	function save()
	{
		global $VALUTA, $ALLOWED_FILES;
		$user_id = intval(@$_POST['user_id']);
		if(!$this->MUser->isCanOper($user_id))
		{
			return;
		}
		$user = $this->MUser->get($user_id);
		if(@$_POST['oper_id'])
		{
			$oper_id = intval($_POST['oper_id']);
			$oper = $this->MOper->get($oper_id);
			if(!canSell($oper, $user))
			{
				return;
			}
			$date = dateToDb($_POST['year']."-".$_POST['month']."-".$_POST['day']);

/* Оформление платежа */

			$platezh_id = intval($_POST['platezh_id']);
			if($platezh_id == -1)
			{
				$platezh_id = 0;
			}
			elseif($platezh_id == 0) 
			{
				$schet_id = intval(@$_POST['platezh_schet_id']);
				$schet = $this->MSchet->get($schet_id);
				if(@$schet['id'])
				{
					$platezh_type = 'sell';
					$platezh_to_user_id = $user['id'];
					$platezh_people = null;
					if($schet['user_id'] != Auth::$user_id)
					{
						$platezh_type = 'sell.drugoy';
						$platezh_to_user_id = 0;
						$platezh_people = $user['fio'];
					}
					$save_platezh = array(
						'schet_id' => intval(@$schet['id']),
						'from_date' => $date,
						'to_date ' => $date,
						'summ' => round(getFloat(@$_POST['platezh_summ']), 2),
						'valuta' => @$_POST['platezh_valuta'],
						'komiss' => round(getFloat(@$_POST['platezh_komiss']), 2),
						'type' => $platezh_type,
						'from_user_id' => $schet['user_id'],
						'to_user_id' => $platezh_to_user_id,
						'people' => $platezh_people,
						'comment' => trim($_POST['dop']),
					);
					for($i = 1; $i <= 5; $i++)
					{
						if(@$_FILES['file'.$i]['name'] && is_uploaded_file($_FILES['file'.$i]['tmp_name']))
						{
							$ex = strtolower(end(explode(".", $_FILES['file'.$i]['name'])));
							if(in_array($ex, $ALLOWED_FILES))
							{
								$filename = Auth::$user_id."_".md5(microtime()).".".$ex;
								if(move_uploaded_file($_FILES['file'.$i]['tmp_name'], UPLOAD_PATH.$filename))
								{
									$save_platezh['file'.$i] = $filename;
								}
							}
							else
							{
								$this->session->set_flashdata('system_error', 'Вы загрузили запрещённый тип файла: '.$_FILES['file'.$i]['name'].". Он не добавился к платежу.");
							}
							$save_platezh['file'.$i.'_comment'] = trim($_POST['file'.$i.'_comment']) == 'Комментарий' ? null : trim($_POST['file'.$i.'_comment']);
						}
					}
					if(@$save_platezh['summ'])
					{
						$this->MPlatezh->save($save_platezh, $platezh_id);
					}
				}
			}

/* Добавление продажи */

			if($oper['type'] == 'week')
			{
				$valuta = $oper['valuta'];
				$summ = round($oper['summ'] * 1.1, 4);
				$mavro_valuta = $oper['mavro_valuta'];
				$kurs = 0;
				$kurs_valuta = 0;
				$mavro = 0;
				$percent = 10;
				$depo = '';
			}
			else
			{
				$percent = $oper['percent'];
				$mavro = min(round(getFloat($_POST['mavro_summ']), 4), $oper['mavro']);
				$mavro_valuta = $oper['mavro_valuta'];
				$kurs = @$_POST['use_kurs_sale_buy'] ? $oper['kurs'] : $this->MKurs->getKurs($date, $percent, 'sell');
				$valuta = @$_POST['use_kurs_sale_buy'] ? $oper['valuta'] : @$_POST['valuta'];
				$kurs_valuta = $mavro_valuta == $valuta ? 1 : getFloat(@$_POST['kurs_valuta']);
				$kurs_valuta = $kurs_valuta > 0 ? $kurs_valuta : 1;
				$summ = @$_POST['kurs_valuta_reverse'] ? $mavro * $kurs / $kurs_valuta : $mavro * $kurs * $kurs_valuta;
				$summ = round($summ, 4);
				$depo = $oper['depo'];
			}

			$save = array(
				'user_id' => $user['id'],
				'platezh_id' => $platezh_id,
				'parent_id' => $oper['id'],
				'date' => $date,
				'type' => 'sell',
				'bonus' => 0,
				'summ' => $summ,
				'valuta' => $valuta,
				'kurs' => $kurs,
				'kurs_valuta' => $kurs_valuta,
				'percent' => $percent,
				'depo' => $depo,
				'mavro' => $mavro,
				'mavro_valuta' => $mavro_valuta,
				'hranen' => trim($_POST['hranen']),
				'dop' => trim($_POST['dop']),
			);
			$id = 0;
			$this->MOper->save($save, $id);
			
/* редактирование остатка старой операции */

			if(isBuy($oper))
			{
				$ostatok = $oper['ostatok'] - $save['mavro'];
				$arr_ostatok = array('ostatok' => round($ostatok, 4));
				$this->MOper->save($arr_ostatok, $oper['id']);
				$oper['ostatok'] = $arr_ostatok['ostatok'];
				operUpdateFrozen($oper);
			}

/* Если нужно, то проводим сгорание бонусов */
			
			if(@$_POST['del_bonus'])
			{
				global $USER_LEVEL;
				$this->load->library('Operation');
				$root = $this->operation->getRoot($oper);
				$this->operation->addSellFire($root, $date, 'ng');
				$this->operation->addSellFire($root, $date, 'patriot');
				$this->operation->addSellFire($root, $date, 'arest');
				$this->operation->addSellFire($root, $date, '8marta');
				$this->operation->addSellFire($root, $date, 'ref');
				foreach($USER_LEVEL as $k => $v)
				{
					$this->operation->addSellFire($root, $date, 'l'.$k);
				}
			}

		}
		redirect('oper/?last_oper='.$id);
	}


	function mass()
	{
		global $VALUTA, $USER_LEVEL, $TYPE_OPER;
		$user_id = intval(@$_GET['user_id']);
		$type = trim(@$_GET['type']);
		if($this->MUser->isMyChild($user_id) && isset($TYPE_OPER[$type]) && ($type == 'ref' || substr($type, 0, 2) == 'l*'))
		{
			$user = $this->MUser->get($user_id);
			$type_filter = $type;
			$filters_oper = array('type' => $type_filter, 'user_id' => $user['id'], 'ostatok>' => '0', 'sort' => 'date asc,id asc');
			if(@$_GET['nofrozen'])
			{
				$filters_oper['date<'] = date("Y-m-d", strtotime("-1 month"));
			}
			$opers = $this->MOper->getList($filters_oper);
			$kurses = $this->_getKurses();

			$root = $this->MUser->getRoot();
			$root['children'] = $this->MUser->getMyStructure($root['id']);

			$my_scheta = $this->MSchet->getList(array('user_id' => Auth::$user_id));
			foreach($my_scheta as $k => $s)
			{
				$my_scheta[$k]['name'] .= " ".$VALUTA[$s['valuta']];
			}


			$view = 'sell_mass_2';
			$data = array('kurses' => $kurses, 'user' => $user, 'opers' => $opers, 'root' => $root, 'my_scheta' => $my_scheta);
		}
		else
		{
			$users = $this->MUser->getChildrenAndMe(Auth::$user_id);
			$me = $this->MUser->get(Auth::$user_id);
			$error = $user_id ? "По участнику не возможна операция продажи" : '';

			$types = array('ref' => $TYPE_OPER['ref']);
			foreach($TYPE_OPER as $k => $v)
			{
				if(substr($k, 0, 2) != 'l*')
				{
					continue;
				}
				$l = str_replace("l", "", $k);
				if(strlen($l) <= strlen($me['level']))
				{
					$types[$k] = $v;
				}
				elseif($this->MOper->getCount(array('user_id' => $me['id'], 'type' => $k)))
				{
					$types[$k] = $v;
				}
				else
				{
					break;
				}
			}


			$data = array('users' => $users, 'me' => $me, 'types' => $types, 'error' => $error);
			$view = 'sell_mass_1';
		}
		$this->load->view('head', array());
		$this->load->view('oper/'.$view, $data);
		$this->load->view('foot');
	}

	function mass_save()
	{
		global $VALUTA, $USER_LEVEL_BONUS_TXT, $ALLOWED_FILES;
		$user_id = intval($_POST['user_id']);
		if(!$this->MUser->isMyChild($user_id) || !is_array($_POST['oper_id']) || !count($_POST['oper_id']))
		{
			return;
		}

		$user = $this->MUser->get($user_id);
		$opers = $this->MOper->getList(array('id' => $_POST['oper_id']));
		$date = dateToDb($_POST['year']."-".$_POST['month']."-".$_POST['day']);

/* Оформление платежа */

		$platezh_id = intval($_POST['platezh_id']);
		if($platezh_id == -1)
		{
			$platezh_id = 0;
		}
		elseif($platezh_id == 0) 
		{
			$schet_id = intval(@$_POST['platezh_schet_id']);
			$schet = $this->MSchet->get($schet_id);
			if(@$schet['id'])
			{
				$platezh_type = 'sell';
				$platezh_to_user_id = $user['id'];
				$platezh_people = null;
				if($schet['user_id'] != Auth::$user_id)
				{
					$platezh_type = 'sell.drugoy';
					$platezh_to_user_id = 0;
					$platezh_people = $user['fio'];
				}
				$save_platezh = array(
					'schet_id' => intval(@$schet['id']),
					'from_date' => $date,
					'to_date ' => $date,
					'summ' => round(getFloat(@$_POST['platezh_summ']), 2),
					'valuta' => @$_POST['platezh_valuta'],
					'komiss' => round(getFloat(@$_POST['platezh_komiss']), 2),
					'type' => $platezh_type,
					'from_user_id' => @$schet['user_id'],
					'to_user_id' => $platezh_to_user_id,
					'people' => $platezh_people,
					'comment' => trim($_POST['dop']),
				);
				for($i = 1; $i <= 5; $i++)
				{
					if(@$_FILES['file'.$i]['name'] && is_uploaded_file($_FILES['file'.$i]['tmp_name']))
					{
						$ex = strtolower(end(explode(".", $_FILES['file'.$i]['name'])));
						if(in_array($ex, $ALLOWED_FILES))
						{
							$filename = Auth::$user_id."_".md5(microtime()).".".$ex;
							if(move_uploaded_file($_FILES['file'.$i]['tmp_name'], UPLOAD_PATH.$filename))
							{
								$save_platezh['file'.$i] = $filename;
							}
						}
						else
						{
							$this->session->set_flashdata('system_error', 'Вы загрузили запрещённый тип файла: '.$_FILES['file'.$i]['name'].". Он не добавился к платежу.");
						}
						$save_platezh['file'.$i.'_comment'] = trim($_POST['file'.$i.'_comment']) == 'Комментарий' ? null : trim($_POST['file'.$i.'_comment']);
					}
				}
				if($save_platezh['summ'])
				{
					$this->MPlatezh->save($save_platezh, $platezh_id);
				}
			}
		}

/* Запись в базу */

		$mavro = 0;
		$type = '';
		$from_oper_id = array();
		foreach($opers as $o)
		{
			$mavro += $o['ostatok'];
			$mavro_valuta = $o['mavro_valuta'];
			$type = $o['type'];
			$from_oper_id[] = $o['id'];
			$percent = $o['percent'];
		}
		$kurs = $this->MKurs->getKurs($date, $percent, 'sell');
		$valuta = @$_POST['valuta'];
		$kurs_valuta = $mavro_valuta == $valuta ? 1 : getFloat(@$_POST['kurs_valuta']);
		$kurs_valuta = $kurs_valuta > 0 ? $kurs_valuta : 1;
		$summ = @$_POST['kurs_valuta_reverse'] ? $mavro * $kurs / $kurs_valuta : $mavro * $kurs * $kurs_valuta;
		$summ = round($summ, 4);
		$save = array(
			'platezh_id' => $platezh_id,
			'user_id' => $user['id'],
			'date' => $date,
			'type' => 'sell.mass',
			'bonus' => 0,
			'summ' => $summ,
			'valuta' => $valuta,
			'kurs' => $kurs,
			'kurs_valuta' => $kurs_valuta,
			'percent' => $percent,
			'mavro' => $mavro,
			'mavro_valuta' => $mavro_valuta,
			'hranen' => trim($_POST['hranen']),
			'dop' => trim($_POST['dop']),
		);
		$id = 0;
		$this->MOper->save($save, $id);
		$this->MOper->addMass($from_oper_id, $id, $date);

		redirect('oper/?u[]='.$user['id']);
	}






	/*********************************************/

	private function _getKurses()
	{
		$kurses = $this->MKurs->getList();
		$out = array();
		$last_kurs_value = array();
		foreach($kurses as $kurs)
		{
			$k = $kurs['sell'] ? $kurs['sell'] : (@$last_kurs_value[$kurs['percent']] ? $last_kurs_value[$kurs['percent']] : $kurs['buy']);
			$out[$kurs['date']][intval($kurs['percent'])] = array('buy' => $kurs['buy'], 'sell' => $k);
			$last_kurs_value[$kurs['percent']] = $kurs['buy'];
		}
		return $out;
	}






	
}
